#!/usr/bin/env node

import { DatabaseManager } from '../src/database/DatabaseManager.js';
import { LoggingService } from '../src/logging/LoggingService.js';

/**
 * 日志功能测试脚本
 */
async function testLoggingService() {
  console.log('🧪 开始测试日志记录功能...');
  
  let dbManager;
  let loggingService;
  
  try {
    // 1. 初始化数据库
    console.log('📊 初始化数据库连接...');
    dbManager = new DatabaseManager();
    await dbManager.initialize();
    
    // 2. 初始化日志服务
    console.log('📝 初始化日志服务...');
    loggingService = LoggingService.getInstance(dbManager.getRepositories());
    const sessionId = loggingService.generateSessionId();
    console.log(`🆔 会话ID: ${sessionId}`);
    
    // 3. 模拟一些工具调用日志
    console.log('🔧 模拟工具调用...');
    
    // 模拟成功的代码生成调用
    const measure1 = loggingService.createMeasure('generate_antd_code', {
      component: 'Button',
      framework: 'react',
      props: { type: 'primary', size: 'large' }
    });
    
    // 模拟50ms的执行时间
    await new Promise(resolve => setTimeout(resolve, 50));
    await measure1.success({ 
      codeGenerated: true, 
      codeLength: 420 
    });
    
    console.log('✅ 记录了代码生成调用');
    
    // 模拟搜索组件调用
    const measure2 = loggingService.createMeasure('search_antd_components', {
      query: 'table',
      category: 'data-display',
      limit: 10
    });
    
    await new Promise(resolve => setTimeout(resolve, 30));
    await measure2.success({ 
      resultCount: 5 
    });
    
    console.log('✅ 记录了搜索组件调用');
    
    // 模拟一个错误调用
    const measure3 = loggingService.createMeasure('get_antd_documentation', {
      component: 'NonExistentComponent'
    });
    
    await new Promise(resolve => setTimeout(resolve, 20));
    await measure3.error('Component not found: NonExistentComponent');
    
    console.log('❌ 记录了错误调用');
    
    // 4. 等待日志刷新到数据库
    console.log('⏳ 等待日志刷新到数据库...');
    await new Promise(resolve => setTimeout(resolve, 2000));
    
    // 手动刷新日志
    loggingService.cleanup();
    await new Promise(resolve => setTimeout(resolve, 1000));
    
    // 5. 获取使用统计
    console.log('📊 获取使用统计...');
    const analytics = await loggingService.getUsageAnalytics();
    
    console.log(`📈 总调用次数: ${analytics.totalCalls}`);
    console.log(`📈 成功率: ${(analytics.successRate * 100).toFixed(1)}%`);
    console.log(`📈 平均执行时间: ${analytics.avgExecutionTime.toFixed(1)}ms`);
    
    if (analytics.topTools.length > 0) {
      console.log('🔥 热门工具:');
      analytics.topTools.forEach((tool, i) => {
        console.log(`  ${i + 1}. ${tool.toolName}: ${tool.calls}次`);
      });
    }
    
    // 6. 获取最近的日志
    console.log('\n📝 获取最近的调用日志...');
    const recentLogs = await loggingService.getRecentLogs(10);
    
    console.log(`📋 找到 ${recentLogs.length} 条日志记录:`);
    recentLogs.forEach((log, i) => {
      const status = log.status === 'success' ? '✅' : '❌';
      console.log(`  ${i + 1}. ${status} [${log.tool_name}] ${log.execution_time_ms}ms - ${new Date(log.created_at!).toLocaleString()}`);
      if (log.error_message) {
        console.log(`     错误: ${log.error_message}`);
      }
    });
    
    // 7. 获取每日报告
    console.log('\n📅 获取每日报告...');
    const today = new Date().toISOString().split('T')[0];
    const dailyReport = await loggingService.getDailyReport(today);
    
    console.log(`📊 ${dailyReport.date} 日报告:`);
    console.log(`  - 总调用次数: ${dailyReport.summary.totalCalls}`);
    console.log(`  - 成功率: ${(dailyReport.summary.successRate * 100).toFixed(1)}%`);
    console.log(`  - 平均响应时间: ${dailyReport.summary.avgExecutionTime.toFixed(1)}ms`);
    
    if (dailyReport.toolBreakdown.length > 0) {
      console.log('🔧 工具使用明细:');
      dailyReport.toolBreakdown.forEach(tool => {
        console.log(`  • ${tool.toolName}: ${tool.calls}次 (✅${tool.successCalls} ❌${tool.errorCalls})`);
      });
    }
    
    console.log('\n🎉 日志功能测试完成！');
    
  } catch (error) {
    console.error('❌ 测试失败:', error);
  } finally {
    // 清理资源
    if (loggingService) {
      loggingService.cleanup();
    }
    if (dbManager) {
      await dbManager.close();
    }
  }
}

// 运行测试
testLoggingService().catch(console.error);